package com.shawn.study.kafka;

import java.util.Collections;
import java.util.Properties;
import java.util.Random;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

public class KafkaDemoMain {

  private static final String TOPIC_NAME = "TestTopic";
  private static final String BOOTSTRAP_SERVER = "172.27.67.26:9092";

  public static void main(String[] args) throws Exception{
    testProducer();
    testConsumer();
  }

  private static void testProducer() throws Exception{
    Properties p = new Properties();
    p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVER);//kafka地址，多个地址用逗号分割
    p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(p);
    try {
      int i = 1;
      while (true) {
        if(i > 100){
          break;
        }
        String msg = "Hello," + new Random().nextInt(100);
        ProducerRecord<String, String> record = new ProducerRecord<String, String>(TOPIC_NAME, msg);
        kafkaProducer.send(record);
        System.out.println("消息发送成功:" + msg);
        i++;
        Thread.sleep(500);
      }
    } finally {
      kafkaProducer.close();
    }
  }

  private static void testConsumer() throws Exception{
    Properties p = new Properties();
    p.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVER);
    p.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    p.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    p.put(ConsumerConfig.GROUP_ID_CONFIG, "shawn_test");
    KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(p);
    kafkaConsumer.subscribe(Collections.singletonList(TOPIC_NAME));// 订阅消息
    while (true) {
      ConsumerRecords<String, String> records = kafkaConsumer.poll(100);
      for (ConsumerRecord<String, String> record : records) {
        System.out.println(String.format("topic:%s,offset:%d,消息:%s", //
                record.topic(), record.offset(), record.value()));
      }
    }

  }
}
